/**
 * 
 */
package info.niwota.ispy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.channels.Channels;

/**
 * @author qiangli
 * 
 */
public class Logcat {

	private Logcat() {
	}

	public static final Thread tail(final IQEntryCallback callback) {
		try {
			return tail("logcat", Detect.LOGCAT_ELEMENTS,
					Detect.ELEMENTS_EXCLUDE, callback);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static final Thread tail(String command, final String[] filters,
			final String[] excludes, final IQEntryCallback callback)
			throws IOException {
		final Process p = Runtime.getRuntime().exec(command);
		
		Thread t = new Thread() {
			public void run() {
				BufferedReader in = null;
				try {
					//expensive but only way to be interrupt-able
					in = new BufferedReader(new InputStreamReader(	
					        Channels.newInputStream(Channels.newChannel(p.getInputStream()))));
				
					long count = 0;
					String line;
					next: while ((line = in.readLine()) != null) {
						for (String filter : filters) {
							if (line.contains(filter)) {
								for (String ex : excludes) {
									if (line.contains(ex)) {
										continue next;
									}
								}
								// found
								callback.found(++count, line);
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (in != null) {
						try {
							in.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}

					if (p != null) {
						p.destroy();
					}
				}
			}
		};
		t.start();

		return t;
	}
}
